package com.jd.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jd.basic.exception.BusinessException;
import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.RsaUtils;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.HttpUtil;
import com.jd.basic.util.MD5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.system.domain.Menu;
import com.jd.system.mapper.MenuMapper;
import com.jd.system.mapper.PermissionMapper;
import com.jd.user.constant.WxConstants;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.domain.Wxuser;
import com.jd.user.dto.LoginDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.mapper.WxuserMapper;
import com.jd.user.service.ILogininfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {


    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        // 1.通过account好type去查数据库
        Logininfo logininfo = logininfoMapper.accountLogin(loginDto);
        // 2.判断对象为null--账号错误 -抛异常
        if (logininfo == null) {
            throw new BusinessException("用户名错误");
        } else {
            // 3.不为null -判断密码+盐值
            String inputPwd = MD5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
            if (!inputPwd.equals(logininfo.getPassword())) {
                // 3.1 密码失败
                throw new BusinessException("密码错误");
            } else {

                // 登录成功，jwt
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);


//                // 3.2 登录成功
//                String token = UUID.randomUUID().toString();
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//                // 4.将token和对象存在map，然后返回
//                Map<String, Object> map = new HashMap<>();
//                map.put("token",token);
//                logininfo.setPassword(null);
//                logininfo.setSalt(null);
//                map.put("logininfo",logininfo);
                return map;
            }

        }

    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("logininfo", logininfo);
        // 封装成一个logindata对象
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);

        if (logininfo.getType() == 0) { // 管理员
            // 1.如果是后台管理员--获取当前登录人【logininfo.getId()】获取所以菜单0
            List<Menu> menus = menuMapper.getMenuByLogininfoId(logininfo.getId());

            // 2.如果是前端管理员--获取当前登录人【logininfo.getId()】获取所以权限
            List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
            // 封装成一个LoginDate对象
            loginData.setPermissions(permissions);
            loginData.setMenus(menus);
            map.put("menus", menus);
            map.put("permissions", permissions);
        }
            try {
                // 3.获取私钥
                PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
                // 4.获取私钥对LoginDate对象进行加密，加密jwt字符串
                String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);

                // 5.logininfo、所以菜单、所以权限、jwttoken都要封装到map
                // 6.logininfo 返回给前端 - 登录权限
                // 7.所以菜单--返回给前端 - 动态路由- 实现动态菜单
                // 8.所以权限--返回给权限- 资源权限
                // 9.jwttoken 进行解密
                map.put("token", jwtToken);

            } catch (Exception e) {
                e.printStackTrace();
            }

            return map;

            // 将map响应给前端



        }


    // 微信登录
    @Override
    public AjaxResult wechatLogin(String code) {
        // 1.准备请求和替换参数
        String url =  WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        // 2.使用HttpUtil发送请求
        String jsonStr = HttpUtil.httpGet(url);

        // 3.返回的json字符串处理
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 4.根据opdnid去查找t_wxuser对象
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        // 4.1 如果有 -绑定前端 返回return true
        if (wxuser != null && wxuser.getUserId() != null){
            // 通过userId查询user对象
            User user = userMapper.loadById(wxuser.getUserId());
            if (user != null){
                // 通过user对象的logininfoId查询logininfo对象
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

                // 登录成功，jwt
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);


//                String token = UUID.randomUUID().toString();
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//                // 4.将token和对象存在map，然后返回
//                Map<String, Object> map = new HashMap<>();
//                map.put("token",token);
//                logininfo.setPassword(null);
//                logininfo.setSalt(null);
//                map.put("logininfo",logininfo);





                return AjaxResult.me().setResultObj(map);
            }
        }

        // 4.2 如果没有绑定 返回return false
        String params = "?accessToken="+accessToken+"&openId="+openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);

    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        // 1.校验: 空值效验 手机号码和验证码
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能够为null");
        }
        // 2.校验: 校验手机验证码是否正确和过期
        Object codeObj = redisTemplate.opsForValue().get("binder:" + phone);
        if (codeObj == null){
            throw new BusinessException("手机验证码过期");
        }
        if (!codeObj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误");
        }

        // 3.第三个请求替换数据、发送
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);

        // 4.处理json字符串
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        // 5.绑定流程 -phone
        // 5.1 通过phone查询t_user
        User user = userMapper.loadByPhone(phone);
        // 5.2 如果有，直接绑定
        if (user == null){
            // 5.3 如果没有，通过phone创建一个user对象
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        // 将user_id设置到wxuser对象
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());


        // 登录成功，jwt
        Map<String, Object> result = loginSuccessJwtHandler(logininfo);

//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//        //4.将token和登录信息对象对存在Map ，然后返回
//        Map<String, Object> result = new HashMap<>();
//        result.put("token",token); //后续做登录拦截验证
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        result.put("logininfo",logininfo); //让前端显示用户信息


        return AjaxResult.me().setResultObj(result);



    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }


    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机密码
        String randomPwd = StrUtils.getComplexRandomString(4);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        return user;

    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));

        String country = jsonObject.getString("country");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");

        wxuser.setAddress(country+province+city);
        return wxuser;
    }
}
